/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.xgithubclient.fragment;

import android.view.View;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xgithubclient.R;
import com.xuexiang.xgithubclient.activity.MainActivity;
import com.xuexiang.xgithubclient.core.base.BaseFragment;
import com.xuexiang.xgithubclient.core.http.AccountManager;
import com.xuexiang.xgithubclient.core.http.api.request.AuthRequest;
import com.xuexiang.xgithubclient.core.http.api.response.auth.BasicToken;
import com.xuexiang.xgithubclient.core.http.api.response.auth.User;
import com.xuexiang.xgithubclient.core.http.callback.TipJsonCallback;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.edittext.materialedittext.MaterialEditText;
import com.xuexiang.xutil.app.ActivityUtils;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Credentials;

import static com.xuexiang.xgithubclient.core.http.GithubUrl.AUTHORIZATIONS_URL;
import static com.xuexiang.xgithubclient.core.http.GithubUrl.GET_USER_URL;

/**
 * @author xuexiang
 * @since 2019-06-30 18:52
 */
@Page(name = "登陆", anim = CoreAnim.none)
public class LoginFragment extends BaseFragment {

    @BindView(R.id.et_username)
    MaterialEditText etUsername;
    @BindView(R.id.et_password)
    MaterialEditText etPassword;

    @Override
    protected TitleBar initTitle() {
        return super.initTitle().setLeftImageDrawable(ResUtils.getDrawable(R.drawable.ic_action_close_white));
    }

    /**
     * 布局的资源id
     *
     * @return
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_login;
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initViews() {

    }


    @SingleClick
    @OnClick(R.id.sb_submit)
    public void onViewClicked(View view) {
        if (etUsername.validate() && etPassword.validate()) {
            doLogin(etUsername.getEditValue(), etPassword.getEditValue());
        }
    }

    /**
     * 登陆
     *
     * @param username
     * @param password
     */
    private void doLogin(String username, String password) {
        AuthRequest authRequest = AuthRequest.generate();
        String token = Credentials.basic(username, password);
        getMessageLoader("登陆中...").show();
        OkGo.<BasicToken>post(AUTHORIZATIONS_URL)
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(authRequest.toJson())
                .headers("Authorization", token)
                .execute(new TipJsonCallback<BasicToken>() {
                    @Override
                    public void onSuccess(Response<BasicToken> response) {
                        getUserInfo(response.body());
                    }

                    @Override
                    public void onError(Response<BasicToken> response) {
                        super.onError(response);
                        getMessageLoader().dismiss();
                    }
                });

    }

    /**
     * 获取用户信息
     *
     * @param basicToken
     */
    private void getUserInfo(final BasicToken basicToken) {
        OkGo.<User>get(GET_USER_URL)
                .cacheMode(CacheMode.NO_CACHE)
                .headers("Authorization", "token " + basicToken.getToken())
                .execute(new TipJsonCallback<User>() {
                    @Override
                    public void onSuccess(Response<User> response) {
                        AccountManager.get().handleLoginSuccess(basicToken, response.body());
                        ActivityUtils.startActivity(MainActivity.class);
                        popToBack();
                    }

                    @Override
                    public void onFinish() {
                        getMessageLoader().dismiss();
                    }
                });

    }


}
